/*
 * @(#)FletcherReeves.java        1.0 2000/06/26
 *
 * This file is part of Xfuzzy 3.0, a design environment for fuzzy logic
 * based systems.
 *
 * (c) 2000 IMSE-CNM. The authors may be contacted by the email address:
 *                    xfuzzy-team@imse.cnm.es
 *
 * Xfuzzy is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by
 * the Free Software Foundation.
 *
 * Xfuzzy is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * for more details.
 */

package xfuzzy.xfsl.model.algorithm;

import xfuzzy.xfsl.model.*;
import xfuzzy.lang.*;
import xfuzzy.xfds.XfdsDataSet;

/**
 * Versi�n de Fletcher-Reeves del algoritmo de gradiente conjugado
 * 
 * @author Francisco Jos� Moreno Velo
 * 
 * @see "Scales, L.E., Introduction to Non-Linear Optimization, 
 * Springer-Verlag New York Inc., 1985."
 *
 */
public class FletcherReeves extends XfslGradientBasedAlgorithm {

	//----------------------------------------------------------------------------//
	//                            MIEMBROS PRIVADOS                               //
	//----------------------------------------------------------------------------//

	/**
	 * �ltima direcci�n de optimizaci�n
	 */
	private double[] last_p;
	
	/**
	 * Contador de iteraciones
	 */
	private int iter;
	
	/**
	 * Factor de tolerancia en la b�squeda lineal
	 */
	private double tol;
	
	/**
	 * L�mite de iteraciones en la b�squeda lineal
	 */
	private int limit;

	//----------------------------------------------------------------------------//
	//                                CONSTRUCTOR                                 //
	//----------------------------------------------------------------------------//

	/**
	 * Constructor
	 */
	public FletcherReeves() {
		this.iter = 0;
		this.tol = 0.1;
		this.limit = 10;
	}

	//----------------------------------------------------------------------------//
	//                             M�TODOS P�BLICOS                               //
	//----------------------------------------------------------------------------//

	/**
	 * Devuelve el c�digo de identificaci�n del algoritmo
	 */
	public int getCode() {
		return FLETCHER_REEVES;
	}

	/**
	 * Actualiza los par�metros de configuraci�n del algoritmo
	 */
	public void setParameters(double[] param) throws XflException {
		if(param.length != 2) throw new XflException(26);
		tol = test(param[0], REDUCE);
		limit = (int) test(param[1], INTEGER);
	}

	/**
	 * Obtiene los par�metros de configuraci�n del algoritmo
	 */
	public XfslAlgorithmParam[] getParams() {
		XfslAlgorithmParam[] pp = new XfslAlgorithmParam[2];
		pp[0] = new XfslAlgorithmParam(tol, 0.1, REDUCE, "Line-search Tolerance");
		pp[1] = new XfslAlgorithmParam(limit, 10, INTEGER, "Search Iteration Limit");
		return pp;
	}

	/**
	 * Ejecuta una iteraci�n del algoritmo
	 */
	public XfslEvaluation iteration(Specification spec, XfdsDataSet pattern,
			XfslErrorFunction ef) throws XflException {
		XfslEvaluation prev = computeErrorGradient(spec,pattern,ef);
		OptimizingFunction function = new OptimizingFunction(spec,pattern,ef);
		Parameter[] param = spec.getAdjustable();
		double[] pt = new double[param.length];
		for(int i=0; i<param.length; i++) pt[i] = param[i].value;
		boolean reset = false;

		if(init) { init = false; iter = 0; reset = true;} else iter++; 
		if(iter == param.length) { reset = true; iter = 0; }

		double[] g = new double[param.length];
		for(int i=0; i<param.length; i++) g[i] = -param[i].getDeriv();
		double[] p;
		if(reset) p = g; else p = searchDirection(param,last_p);

		XfslEvaluation eval = function.linmin(p,prev,tol,limit);

		for(int i=0; i<param.length; i++) {
			param[i].setPrevDesp(param[i].value - pt[i]);
			param[i].setPrevDeriv(-g[i]);
			param[i].setDeriv(0);
		}

		last_p = p;
		return eval;
	}

	//----------------------------------------------------------------------------//
	//                             M�TODOS PRIVADOS                               //
	//----------------------------------------------------------------------------//

	/**
	 * Calcula la direcci�n conjugada
	 */
	private double[] searchDirection(Parameter[] param, double[] p) {
		double[] d = new double[param.length];
		double num=0, den=0;
		for(int i=0; i<param.length; i++) {
			double g = param[i].getDeriv();
			double pg = param[i].getPrevDeriv();
			num += g*g;
			den += pg*pg;
		}
		double B = num/den;
		for(int i=0; i<param.length; i++) d[i] = -param[i].getDeriv() + B*p[i];
		return d;
	}
}

